<template>
  <div class="user-list">
    <!-- 面包屑 -->
    <el-row>
      <my-breadcrumb level1="用户管理" level2="用户列表"></my-breadcrumb>
    </el-row>
    <!-- 搜索 -->
    <el-row :gutter="20">
      <el-col :span="10">
        <el-input
          placeholder="请输入内容"
          v-model="query"
          @clear="getUserListData"
          @keyup.native.enter="getUserListData"
          clearable
          class="input-with-select"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="getUserListData"
          ></el-button>
        </el-input>
      </el-col>
      <el-col :span="3">
        <el-button type="success" icon="el-icon-circle-plus-outline" plain @click="dialogVisibleAdd = true"
          >添加用户</el-button
        >
      </el-col>
    </el-row>
    <!-- 表格 -->
    <el-row>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" label="#" width="60"></el-table-column>
        <el-table-column prop="username" label="名称" width="120">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="160">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="160">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="权限名称"
          width="120"
        ></el-table-column>
        <el-table-column label="创建时间" width="120">
          <template slot-scope="scope">
            {{ scope.row.create_time | fmBaseDateStyle }}
          </template>
        </el-table-column>
        <el-table-column label="用户状态" width="120">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="switchUserStatus(scope.row)"
              :disabled="scope.row.username === 'admin'"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="操作" width="140">
          <template slot-scope="scope">
            <el-row>
              <el-tooltip effect="dark" content="编辑" placement="top">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  plain
                  size="mini"
                  @click="handleEditUser(scope.row)"
                  :disabled="scope.row.username === 'admin'"
                ></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="删除" placement="top">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  plain
                  size="mini"
                  @click="handleDeleteUser(scope.row)"
                  :disabled="scope.row.username === 'admin'"
                ></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="角色" placement="top">
                <el-button
                  type="warning"
                  icon="el-icon-s-tools"
                  circle
                  plain
                  size="mini"
                  @click="handleAuthUser(scope.row)"
                  :disabled="scope.row.username === 'admin'"
                ></el-button>
              </el-tooltip>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <!-- 分页 -->
    <el-row>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-row>
    <!-- 添加用户 -->
    <user-add
      :dialogVisibleAdd="dialogVisibleAdd"
      @addUserClosed="dialogVisibleAdd = false"
      @addUserSuccess="getUserListData"
    ></user-add>
    <!-- 编辑用户 -->
    <user-edit
      :dialogVisibleEdit="dialogVisibleEdit"
      :userInfo="currUserInfo"
      @editUserClosed="dialogVisibleEdit = false"
      @editUserSuccess="getUserListData"
    ></user-edit>
    <!-- 分配角色 -->
    <user-auth
      :dialogVisibleAuth="dialogVisibleAuth"
      :userInfo="currUserInfo"
      @authUserClosed="dialogVisibleAuth = false"
      @authUserSuccess="getUserListData"
    ></user-auth>
  </div>
</template>

<script>
import MyBreadcrumb from '@/components/MyBreadcrumb'

import UserAdd from '@/views/users/components/UserAdd'
import UserEdit from '@/views/users/components/UserEdit'
import UserAuth from '@/views/users/components/UserAuth'
export default {
  components: {
    MyBreadcrumb,
    UserAdd,
    UserEdit,
    UserAuth
  },
  data() {
    return {
      query: '',
      tableData: [],
      total: 0,
      pageSize: 5,
      pageNum: 1,
      dialogVisibleAdd: false,
      dialogVisibleEdit: false,
      dialogVisibleAuth: false,
      currUserInfo: null
    }
  },
  created() {
    this.getUserListData()
  },
  computed: {},
  methods: {
    async getUserListData() {
      // 设置请求头
      // this.$http.defaults.headers.common[
      //   'Authorization'
      // ] = localStorage.getItem('token')

      const { data } = await this.$http.get('/users', {
        params: {
          query: this.query,
          pagenum: this.pageNum,
          pagesize: this.pageSize
        }
      })

      // console.log(data)
      if (data.meta.status === 200) {
        const { total, users } = data.data
        this.tableData = users
        this.total = total
      } else {
        this.$message.warning(data.meta.msg)
      }
    },
    // 修改用户状态
    async switchUserStatus(userInfo) {
      const { id, mg_state: mgState } = userInfo
      const {
        data: { meta }
      } = await this.$http.put(`users/${id}/state/${mgState}`)

      if (meta.status === 200) {
        this.$message.success(meta.msg)
      } else {
        this.$message.error(meta.msg)
      }
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pageSize = val
      // 切换每页数据条目数量的时候，页码切回到 1
      this.pageNum = 1
      this.getUserListData()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.pageNum = val
      this.getUserListData()
    },

    // 删除按钮
    handleDeleteUser(userInfo) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const {
            data: { meta }
          } = await this.$http.delete('/users/' + userInfo.id)

          if (meta.status === 200) {
            this.$message.success(meta.msg)
            this.getUserListData()
          } else {
            this.$message.error(meta.msg)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑用户
    handleEditUser(userInfo) {
      this.dialogVisibleEdit = true
      this.currUserInfo = JSON.parse(JSON.stringify(userInfo))
    },
    // 分配角色
    handleAuthUser(userInfo) {
      this.dialogVisibleAuth = true
      this.currUserInfo = JSON.parse(JSON.stringify(userInfo))
    }
  }
}
</script>

<style lang="less" scoped>
.user-list {
  .el-row {
    padding: 5px 0;
  }
}
</style>
